﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace PlatesWorkshop.Services
{
    public class BackgroundCommunicationHostedService : BackgroundService
    {

        private readonly ILogger<BackgroundCommunicationHostedService> _logger;

        public IServiceProvider Services { get; }
        public BackgroundCommunicationHostedService(IServiceProvider services,
            ILogger<BackgroundCommunicationHostedService> logger)
        {
            Services = services;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation(
                "Background Service running.");


            using (var scope = Services.CreateScope())
            {
                var kepWareService =
                    scope.ServiceProvider
                        .GetRequiredService<KepWareOpcService>();

                await kepWareService.Connect("opc.tcp://10.61.140.18:49320");
                _logger.LogInformation(
                "Connect comolete.");
                kepWareService.CreateSubscription();
            }
        }

        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation(
                "Consume Scoped Service Hosted Service is stopping.");

            await Task.CompletedTask;
        }








    }
}
